from time import strftime,time
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
import re
import pypandoc
import base64
import hmac
import json

# 汉字转拼音
from xpinyin import Pinyin
pinyin = Pinyin()




ROOTDIR = os.path.dirname(__file__)

# 数据库连接
CONNECTION = f'sqlite:///{ROOTDIR}/botData.db'
# f"mysql+pymysql://root:{quote('pwd')}@127.0.0.1:3306/qqbot?charset=utf8",

if CONNECTION.startswith('sqlite'):
    engine = create_engine(
        CONNECTION,
        # echo=True,
        pool_recycle=-1,
        pool_pre_ping=True
    )
else:
    engine = create_engine(
        CONNECTION,
        # echo=True,
        max_overflow=10,
        pool_size=40,
        pool_recycle=-1,
        pool_pre_ping=True
    )

def makeNewSession():
    Session = sessionmaker(bind=engine)
    session = scoped_session(Session)
    # session = Session()
    return session









## token key
TOKEN_KEY = ""
# 运行端口
PORT = 5701
# 发送消息给go-cqhttp
HOST="127.0.0.1"
SENDPORT=5700

# 静态文件目录
STATIC_PATH = os.path.join(ROOTDIR, 'static')
# 文件上传下载
UPLOADDIR = os.path.join(ROOTDIR,"uploadfiles")
# forms 自定义表单
FORMDIR = os.path.join(ROOTDIR, "forms")
FORMPROTOTYPE = os.path.join(FORMDIR, 'form_prototype.html')
LAYUI_CSS_PATH = os.path.relpath(os.path.join(STATIC_PATH, 'css', 'layui.css'),FORMDIR)
LAYUI_JS_PATH = os.path.relpath(os.path.join(STATIC_PATH, 'layui.js'),FORMDIR)
AXIOS_PATH =  os.path.relpath(os.path.join(STATIC_PATH, "js", "axios.min.js"),FORMDIR)
TABLESELECT_JS = os.path.relpath(os.path.join(STATIC_PATH, "js", "lay-module", "tableSelect","tableSelect.js"),FORMDIR)
PROTOTYPE_JS = os.path.relpath(os.path.join(STATIC_PATH, "js", "prototype_form.js"),FORMDIR)

# form表单提交数据
# FOMR_TABLE_LENGTH = 50
FORM_UPLOAD_FILES_DIR = os.path.join(ROOTDIR, "formUploadFiles") # 表单提交文件目录

# # 检验pandoc是否安装
# pypandoc.ensure_pandoc_installed()

# 临时zip路径
ZIP_DIR = os.path.join(ROOTDIR, "zip_dir")
ZIP_FILE = os.path.join(ZIP_DIR, "temp.zip")
# 临时 Excel 路径
EXCEL_PATH = os.path.join(ROOTDIR, "excels", "temp.xlsx") 

# 主人
MASTER="xxxx"  # 主人QQ号

# 外部访问地址
OUT_ADDRESS = "http://127.0.0.1:5701"

# Timer
INTERVAL = 15*60
TIMER_NO_CHANGE = True






def log(*args, **kwargs):
    print(strftime("[%Y-%m-%d %H:%M:%S] "), *args, **kwargs)


def debug(*args, **kwargs):
    print("DEBUG !!", *args, **kwargs)



def safe_file_name(fName):
    return re.sub(r"[^\u4E00-\u9FA5A-Za-z0-9_\.]", '_', fName)




def fieldName(name):
    return pinyin.get_pinyin(name, '_')

# 计算空格

def calc_space(total:int, use:int, space=' '):
    return space*(total-use)

# 生成token

def generate_token(key, expire=3600):
    r'''
        @Args:
            key: str (用户给定的key，需要用户保存以便之后验证token,每次产生token时的key 都可以是同一个key)
            expire: int(最大有效时间，单位为s)
        @Return:
            state: str
    '''
    ts_str = str(time() + expire)
    ts_byte = ts_str.encode("utf-8")
    sha1_tshexstr  = hmac.new(key.encode("utf-8"),ts_byte,'sha1').hexdigest() 
    token = ts_str+':'+sha1_tshexstr
    b64_token = base64.urlsafe_b64encode(token.encode("utf-8"))
    return b64_token.decode("utf-8")

def certify_token(key, token):
    r'''
        @Args:
            key: str
            token: str
        @Returns:
            boolean
    '''
    token_str = base64.urlsafe_b64decode(token).decode('utf-8')
    token_list = token_str.split(':')
    if len(token_list) != 2:
        return False
    ts_str = token_list[0]
    if float(ts_str) < time():
        # token expired
        return False
    known_sha1_tsstr = token_list[1]
    sha1 = hmac.new(key.encode("utf-8"),ts_str.encode('utf-8'),'sha1')
    calc_sha1_tsstr = sha1.hexdigest()
    if calc_sha1_tsstr != known_sha1_tsstr:
        # token certification failed
        return False 
    # token certification success
    return True 

def init_settings(settings):
    global PORT
    global HOST
    global SENDPORT
    global ROOTDIR
    global CONNECTION
    global STATIC_PATH
    global UPLOADDIR
    global FORMDIR
    global FORMPROTOTYPE
    global LAYUI_CSS_PATH
    global LAYUI_JS_PATH
    global AXIOS_PATH
    global TABLESELECT_JS
    global PROTOTYPE_JS
    global FORM_UPLOAD_FILES_DIR
    global ZIP_DIR
    global ZIP_FILE
    global EXCEL_PATH
    global MASTER
    global OUT_ADDRESS
    global INTERVAL

    PORT = settings.get('PORT')
    HOST = settings.get('HOST')
    SENDPORT = settings.get('SENDPORT')
    ROOTDIR = settings.get('ROOTDIR')
    CONNECTION = settings.get('CONNECTION')
    STATIC_PATH = settings.get('STATIC_PATH')
    UPLOADDIR = settings.get('UPLOADDIR')
    FORMDIR = settings.get('FORMDIR')
    FORMPROTOTYPE = settings.get('FORMPROTOTYPE')
    LAYUI_CSS_PATH = settings.get('LAYUI_CSS_PATH')
    LAYUI_JS_PATH = settings.get('LAYUI_JS_PATH')
    AXIOS_PATH = settings.get('AXIOS_PATH')
    TABLESELECT_JS = settings.get('TABLESELECT_JS')
    PROTOTYPE_JS = settings.get('PROTOTYPE_JS')
    FORM_UPLOAD_FILES_DIR = settings.get('FORM_UPLOAD_FILES_DIR')
    ZIP_DIR = settings.get('ZIP_DIR')
    ZIP_FILE = settings.get('ZIP_FILE')
    EXCEL_PATH = settings.get('EXCEL_PATH')
    MASTER = settings.get('MASTER')
    OUT_ADDRESS = settings.get('OUT_ADDRESS')
    INTERVAL = settings.get('INTERVAL')











if __name__=="__main__":
    for k,v in settings.items():
        print(f"{k} = {v}")


